package com.city.service.report.impl;

import com.city.domain.report.CtMessage;
import com.city.helper.AuthHelper;
import com.city.helper.EntityHelper;
import com.city.repository.report.CtUserBranchRepository;
import com.city.repository.report.MessageRepository;
import com.city.service.report.MessageService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private EntityHelper entityH;
    @Autowired
    private MessageRepository messageR;
    @Autowired
    private CtUserBranchRepository userBranchR;

    @Override
    public CtMessage saveMessage(Integer reportId, String content,String type) {
        JSONObject remarks = new JSONObject();
        remarks.put("reportId",reportId);
        remarks.put("content",content);
        System.out.println(remarks.toString());
        String ct = "申请会办";
        if(type.equals("apply_auth")){ ct = "申请授权" ; }

        CtMessage message = entityH.createMessage(type,0,ct,remarks.toString());
        System.out.println(message);
        return messageR.save(message);
    }

    @Override
    public List<CtMessage> findMessage(Integer userId) {

        List<CtMessage> messageList = new ArrayList<>();
        Integer branchId = userBranchR.findBranchIdByUserId(userId);

        System.out.println(branchId);
        if(branchId != null){
            messageList.addAll(findMessageByAcceptIdAndType(branchId,"申请延期"));
            messageList.addAll(findMessageByAcceptIdAndType(branchId,"申请会办"));
        }
        messageList.addAll(findMessageByAcceptId(userId));
        return messageList;
    }

    @Override
    public CtMessage backMsg(Integer id, String info,Integer taskId) {
        CtMessage message = messageR.findOne(id);
        if(message != null){
            message = entityH.createMessage(message,info,taskId);
            message.setId(id);
            return messageR.save(message);
        }
        return null;
    }

    @Override
    public void save(CtMessage ctMessage) {
        messageR.save(ctMessage);
    }

    private List<CtMessage> findMessageByAcceptId(Integer userId) {
        return messageR.findByAcceptId(userId);
    }

    private List<CtMessage> findMessageByAcceptIdAndType(Integer acceptId,String type) {
        return messageR.findByAcceptIdAndType(acceptId,type);
    }
}
